package com.doyens.seckill.service;

import com.doyens.common.utils.IdWorker;
import com.doyens.seckill.mapper.SeckillGoodsMapper;
import com.doyens.seckill.pojo.SeckillGoods;
import com.doyens.seckill.pojo.SeckillOrder;
import com.doyens.seckill.task.MultiThreadingCreateOrder;
import com.doyens.seckill.utils.SeckillStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.PipedReader;
import java.util.Date;

@Service
public class SeckillOrderService {

    @Autowired
    private RedisTemplate redisTemplate;


    @Autowired
    private MultiThreadingCreateOrder  multiThreadingCreateOrder;

    @Transactional
    public Boolean add(Long id,String time,String username){

        //利用redis的incr递增特性

        Long userQueueCount = redisTemplate.boundHashOps("userQueueCount").increment(username, 1);
        if (userQueueCount > 1){
            System.out.println("重复下单........");
            throw  new   RuntimeException("100");
        }


        //异步调用
        multiThreadingCreateOrder.createOrder();
        //登记排队信息
        SeckillStatus seckillStatus = new SeckillStatus( username, new Date(), 1, id, time);
        //将数据放入到redis的list中去   队列
        redisTemplate.boundListOps("seckillOrderQueue").leftPush(seckillStatus);

        //存储该用户的抢单状态
        redisTemplate.boundHashOps("userQueueStatus").put(username,seckillStatus);

        return true;

    }


    //根据用户查询订单状态
    public SeckillStatus  queryStatus(String username){
        return (SeckillStatus) redisTemplate.boundHashOps("userQueueStatus").get(username);
    }


}
